package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.QuestionnaireIsLock;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 * @Desciption:test
 * @Create by:金木yan
 * @Date: 2021/12/11 15:32
 */
@DubboService
public class QuestionnaireIsLockApiImpl implements QuestionnaireIsLockApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    //根据问卷id和用户id查询问卷是否被锁
    @Override
    public QuestionnaireIsLock findByQuestionnaireId(ObjectId questionnaireId, Long userId) {
        Query query = Query.query(Criteria.where("questionnaireId").is(questionnaireId)
                .and("userId").is(userId));
        QuestionnaireIsLock isLock = mongoTemplate.findOne(query, QuestionnaireIsLock.class);
        return isLock;
    }

    //保存或修改锁数据
    @Override
    public void saveOrUpdate(QuestionnaireIsLock isLock) {
        //1.查询是否存在
        Criteria criteria = Criteria.where("questionnaireId").is(isLock.getQuestionnaireId())
                .and("userId").is(isLock.getUserId());
        Query query = Query.query(criteria);
        //2.判断
        boolean exists = mongoTemplate.exists(query, QuestionnaireIsLock.class);
        if (exists) {
            //存在，修改数据
            Update update = Update.update("isLock", isLock.getIsLock()).set("updated", isLock.getUpdated());
            mongoTemplate.updateFirst(query, update, QuestionnaireIsLock.class);
        } else {
            //不存在，保存
            mongoTemplate.save(isLock);
        }
    }
}
